package com.saxon.shiro.config;

import com.saxon.shiro.pojo.Teacher;
import com.saxon.shiro.service.TeacherService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

public class MyRealm extends AuthorizingRealm {
    @Autowired
    TeacherService teacherService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo (PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo ();
        Subject subject = SecurityUtils.getSubject ();
        Teacher teacher = (Teacher) subject.getPrincipal ();
        simpleAuthorizationInfo.addStringPermission (teacher.getPerm ());
        return simpleAuthorizationInfo;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo (AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        Teacher teacher = teacherService.getTeacherByName (token.getUsername ());
        if (teacher == null) {
            return null;
        }
        return new SimpleAuthenticationInfo (teacher, teacher.getPassword (), "MyRealm");

    }
}
